import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/stores'
import { getCartToOrdersAPI } from '@/apis/order'
import { getAddressAPI } from '@/apis/checkout'

export const useCheckoutStore = defineStore(
  'checkout',
  () => {
    // 获取token
    const userStore = useUserStore()
    // const isLogin = computed(() => userStore.userInfo.token)
    // 定义state
    const checkInfo = ref({})

    // 获取用户地址和购物车商品信息
    const getCheckoutInfo = async () => {
      await getAddressAPI(userStore.userInfo.data.userId).then((res) => {
        checkInfo.value.userAddresses = res.rows
      })

      await getCartToOrdersAPI(userStore.userInfo.data.userId).then((res) => {
        checkInfo.value.details = res.data
      })
    }

    // 获取商品总数量
    const totalCount = computed(() => {
      return checkInfo.value.details.reduce((prev, item) => {
        return prev + item.productQuantity
      }, 0)
    })

    // 获取商品总价
    const totalPrice = computed(() => {
      return checkInfo.value.details.reduce((prev, item) => {
        return prev + item.productPrice * item.productQuantity
      }, 0)
    })
    //清空
    const clearCheckout = () => {
      checkInfo.value = {}
    }
    // 返回
    return { checkInfo, getCheckoutInfo, totalCount, totalPrice, clearCheckout }
  },
  { persist: true }
)
